<template>
  <div class="page-designer">
    <div class="designer-header">
      <div class="header-left">
        <el-icon class="back-icon" @click="$router.back()">
          <ArrowLeft />
        </el-icon>
        <span class="title">{{ pageData.name || '未命名页面' }}</span>
        <el-tag v-if="!isSaved" type="warning" size="small">未保存</el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="handlePreview">
          <el-icon><View /></el-icon>
          预览
        </el-button>
        <el-button @click="showAIDialog = true" type="primary">
          <el-icon><MagicStick /></el-icon>
          AI助手
        </el-button>
        <el-button @click="showCodeDialog = true">
          <el-icon><Document /></el-icon>
          查看代码
        </el-button>
        <el-button type="success" @click="handleSave">
          <el-icon><Select /></el-icon>
          保存
        </el-button>
      </div>
    </div>

    <div class="designer-body">
      <!-- 左侧组件面板 -->
      <div class="component-panel">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="布局组件" name="layout">
            <div class="component-list">
              <div 
                v-for="component in layoutComponents" 
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart(component)"
              >
                <el-icon><Box /></el-icon>
                <span>{{ component.label }}</span>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="数据组件" name="data">
            <div class="component-list">
              <div 
                v-for="component in dataComponents" 
                :key="component.type"
                class="component-item"
                draggable="true"
                @dragstart="handleDragStart(component)"
              >
                <el-icon><Grid /></el-icon>
                <span>{{ component.label }}</span>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 中间画布区域 -->
      <div class="canvas-panel">
        <div class="canvas-toolbar">
          <el-button-group>
            <el-button @click="handleClear">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
            <el-button @click="handleUndo" :disabled="!canUndo">
              <el-icon><RefreshLeft /></el-icon>
              撤销
            </el-button>
          </el-button-group>
        </div>

        <div 
          class="canvas-content"
          @drop="handleDrop"
          @dragover.prevent
        >
          <el-empty v-if="pageComponents.length === 0" description="拖拽左侧组件到此处">
            <el-button type="primary" @click="showAIDialog = true">
              <el-icon><MagicStick /></el-icon>
              使用AI生成
            </el-button>
          </el-empty>

          <div 
            v-for="(component, index) in pageComponents" 
            :key="component.id"
            class="page-component"
            :class="{ active: selectedId === component.id }"
            @click.stop="selectedId = component.id"
          >
            <div class="component-preview">
              <div class="component-label">{{ component.name }}</div>
              <div class="component-mock">{{ component.type }} 组件</div>
            </div>
            
            <div class="component-actions">
              <el-button-group size="small">
                <el-button @click.stop="deleteComponent(index)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧属性面板 -->
      <div class="property-panel">
        <el-tabs v-model="propertyTab">
          <el-tab-pane label="页面属性" name="page">
            <div class="property-form">
              <el-form label-width="80px" size="small">
                <el-form-item label="页面名称">
                  <el-input v-model="pageData.name" />
                </el-form-item>
                <el-form-item label="页面路由">
                  <el-input v-model="pageData.route" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- AI助手对话框 -->
    <el-dialog v-model="showAIDialog" title="AI页面助手" width="600px">
      <el-input
        v-model="aiInput"
        type="textarea"
        :rows="4"
        placeholder="描述你想创建的页面..."
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          生成
        </el-button>
      </template>
    </el-dialog>

    <!-- 代码预览对话框 -->
    <el-dialog v-model="showCodeDialog" title="代码预览" width="800px">
      <pre class="code-preview">{{ generatedCode }}</pre>
      <template #footer>
        <el-button type="primary" @click="showCodeDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="showPreview" title="页面预览" width="90%" fullscreen>
      <div class="page-preview">
        <div v-for="comp in pageComponents" :key="comp.id" class="preview-item">
          {{ comp.name }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, View, MagicStick, Document, Select, Delete,
  RefreshLeft, Box, Grid
} from '@element-plus/icons-vue'

const activeTab = ref('layout')
const propertyTab = ref('page')
const isSaved = ref(true)
const selectedId = ref(null)
const showAIDialog = ref(false)
const showCodeDialog = ref(false)
const showPreview = ref(false)
const aiInput = ref('')
const aiGenerating = ref(false)

const pageData = reactive({
  name: '新建页面',
  route: '/page/new'
})

const pageComponents = ref([])
const history = ref([])
const historyIndex = ref(-1)

const canUndo = computed(() => historyIndex.value > 0)

const generatedCode = computed(() => {
  return `<template>
  <div class="page-container">
    ${pageComponents.value.map(c => `<!-- ${c.name} -->`).join('\n    ')}
  </div>
</template>

<script setup>
// 页面逻辑
<\/script>

<style scoped>
.page-container {
  padding: 20px;
}
</style>`
})

const layoutComponents = [
  { type: 'container', label: '容器' },
  { type: 'card', label: '卡片' },
  { type: 'row', label: '行' }
]

const dataComponents = [
  { type: 'table', label: '表格' },
  { type: 'chart', label: '图表' },
  { type: 'list', label: '列表' }
]

let dragComponent = null

const handleDragStart = (component) => {
  dragComponent = component
}

const handleDrop = () => {
  if (dragComponent) {
    const newComponent = {
      id: `comp_${Date.now()}`,
      type: dragComponent.type,
      name: dragComponent.label
    }
    
    pageComponents.value.push(newComponent)
    isSaved.value = false
    saveHistory()
  }
}

const deleteComponent = (index) => {
  pageComponents.value.splice(index, 1)
  isSaved.value = false
  saveHistory()
}

const handleClear = () => {
  ElMessageBox.confirm('确定要清空吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    pageComponents.value = []
    ElMessage.success('已清空')
  })
}

const saveHistory = () => {
  history.value = history.value.slice(0, historyIndex.value + 1)
  history.value.push(JSON.parse(JSON.stringify(pageComponents.value)))
  historyIndex.value = history.value.length - 1
}

const handleUndo = () => {
  if (canUndo.value) {
    historyIndex.value--
    pageComponents.value = JSON.parse(JSON.stringify(history.value[historyIndex.value]))
  }
}

const handlePreview = () => {
  showPreview.value = true
}

const handleSave = () => {
  console.log('保存页面:', { pageData, components: pageComponents.value })
  isSaved.value = true
  ElMessage.success('保存成功')
}

const handleAIGenerate = () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }

  aiGenerating.value = true

  setTimeout(() => {
    pageComponents.value = [
      { id: 'comp_1', type: 'card', name: '搜索卡片' },
      { id: 'comp_2', type: 'table', name: 'CRUD表格' }
    ]
    
    ElMessage.success('页面生成成功')
    aiGenerating.value = false
    showAIDialog.value = false
    isSaved.value = false
    saveHistory()
  }, 2000)
}

saveHistory()
</script>

<style scoped>
.page-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.designer-header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.designer-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.component-panel {
  width: 260px;
  background: white;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.component-list {
  padding: 10px;
}

.component-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  margin-bottom: 8px;
  background: #f9f9f9;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.component-item:hover {
  background: #409eff;
  color: white;
}

.canvas-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.canvas-toolbar {
  height: 50px;
  background: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.canvas-content {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.page-component {
  margin-bottom: 20px;
  padding: 20px;
  border: 2px dashed transparent;
  border-radius: 4px;
  position: relative;
  transition: all 0.3s;
}

.page-component:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.page-component.active {
  border-color: #409eff;
  border-style: solid;
  background: #f0f9ff;
}

.component-preview {
  min-height: 80px;
}

.component-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.component-mock {
  padding: 20px;
  background: #f5f5f5;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  text-align: center;
  color: #606266;
}

.component-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  opacity: 0;
  transition: opacity 0.3s;
}

.page-component:hover .component-actions {
  opacity: 1;
}

.property-panel {
  width: 300px;
  background: white;
  border-left: 1px solid #e6e6e6;
  overflow-y: auto;
}

.property-form {
  padding: 20px;
}

.code-preview {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
}

.page-preview {
  padding: 20px;
  min-height: 400px;
}

.preview-item {
  padding: 15px;
  margin-bottom: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}
</style>
